package com.dkm.ec.activity.repository.impl;

import com.dkm.base.core.helper.SpringHelper;
import com.dkm.base.db.persistence.dao.IQueryDao;
import com.dkm.biz.repository.AbstractRepository;
import com.dkm.ec.activity.domain.CommonActivitySku;
import com.dkm.ec.activity.persistence.dao.CommonActivitySkuDao;
import com.dkm.ec.activity.persistence.dao.CommonActivitySkuQueryDao;
import com.dkm.ec.activity.persistence.entity.CommonActivitySkuPo;
import com.dkm.ec.activity.repository.CommonActivitySkuRepository;
import com.dkm.ec.stock.persistence.dao.StockDao;
import com.dkm.ec.stock.persistence.dao.StockQueryDao;
import com.dkm.ec.stock.persistence.entity.StockPo;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by fanjinyuan on 2017/8/14.
 */
@Repository
public class CommonActivitySkuRepositoryImpl  extends AbstractRepository<String, CommonActivitySkuPo, CommonActivitySku> implements CommonActivitySkuRepository {

    @Resource
    private CommonActivitySkuQueryDao activitySkuQueryDao;
    @Resource
    private CommonActivitySkuDao commonActivitySkuDao;
    @Resource
    private StockQueryDao stockQueryDao;
    @Resource
    private StockDao stockDao;

    @Override
    public CommonActivitySku newInstance() {
        CommonActivitySkuPo po = new CommonActivitySkuPo();
        CommonActivitySku domain = SpringHelper.getBean(CommonActivitySku.class);
        domain.setData(po);
        return domain;
    }

    @Override
    public CommonActivitySku newInstance(CommonActivitySkuPo po) {
        CommonActivitySku domain = SpringHelper.getBean(CommonActivitySku.class);
        domain.setData(po);
        return domain;
    }

    @Override
    public List<CommonActivitySkuPo> findSKUByPartinId(String partinId) {
        Map<String, Object> params = new HashMap<String, Object>();
        return activitySkuQueryDao.findByKey("findSKUByPartinId", params);
    }

    @Override
    public List<CommonActivitySkuPo> findNeedReturnStockSkus() {
        Map<String, Object> params = new HashMap<String, Object>();
        return activitySkuQueryDao.findByKey("findNeedReturnStockSkus", params);
    }

    @Override
    public void returnStock(List<CommonActivitySkuPo> skuPos) {
        for(CommonActivitySkuPo skuPo : skuPos) {
            // 增加总库存
            StockPo stockPo = stockQueryDao.get(skuPo.getStockid());
            stockPo.setQty(stockPo.getQty() + skuPo.getAvailableNum());
            stockDao.update(stockPo);
            // 更新sku.isReturnStock=1
            skuPo.setAvailableNum(0);
            skuPo.setIsReturnStock("1");
            commonActivitySkuDao.update(skuPo);
        }
    }

    @Override
    protected IQueryDao<String, CommonActivitySkuPo> getQueryDao() {
        return activitySkuQueryDao;
    }

}
